﻿
using ShardingCore.Core.VirtualRoutes;

namespace ApplicationFrame.EntityFrameworkCore.Core
{
    /// <summary>
    /// 哈希分表策略（按分表键哈希取模）
    /// </summary>
    public class HashShardingStrategy<TEntity, TKey> : AbstractShardingStrategy<TEntity, TKey> where TEntity : class
    {
        private readonly int _tableCount;
        private readonly List<string> _list = new List<string>();
        public HashShardingStrategy(string shardingPropertyName, int tableCount)
        {
            _tableCount = tableCount;
            ShardingPropertyName = shardingPropertyName;
        }

        public override string GetTail(TKey shardingKey)
        {
            // 哈希算法：取模（确保均匀分布）
            var hashIndex = 0;
            if (shardingKey is long || shardingKey is ulong || shardingKey is int || shardingKey is uint)
                hashIndex = (int)(Convert.ToUInt64(shardingKey) % (ulong)_tableCount);
            else
                hashIndex = shardingKey.GetHashCode() % _tableCount;

            return $"{hashIndex}";
        }

        //public override List<string> GetTails()
        //{
        //    if (_list.Count > 0)
        //        return _list;

        //    for (var i = 0; i < _tableCount; i++)
        //        _list.Add($"{i}");

        //    return _list;
        //}

        public override Func<string, bool> GetRouteToFilter(TKey shardingKey, ShardingOperatorEnum shardingOperator)
        {
            var t = GetTail(shardingKey);
            return shardingOperator switch
            {
                ShardingOperatorEnum.Equal => (string tail) => t.Equals(tail),
                _ => tail => tail == t,
            };
        }
    }
}
